//
//  PhotoBrowserVC.m
//  XinLang_OC
//
//  Created by WONG on 16/6/11.
//  Copyright © 2016年 cheuhui. All rights reserved.
//

#import "PhotoBrowserVC.h"
#import "PhotoBrowserModel.h"
#import "PhotoBrowserCell.h"
#import "PhotoBrowserModalAnimation.h"
#import "PhotoBrowserDismissAnimation.h"

static NSString * const PhotoBrowserReuseIdentifier = @"PhotoBrowserReuseIdentifier";

@interface PhotoBrowserVC ()<UICollectionViewDataSource,UICollectionViewDelegate,CZPhotoBrowserCellDelegate,UIViewControllerTransitioningDelegate>
/**
 *  图片数据
 */
@property (nonatomic,strong) NSArray<PhotoBrowserModel *> *photoBrowserModels;
/**
 *  点击的cell
 */
@property (nonatomic,strong) NSIndexPath *indexPath;

/**
 *  流水布局
 */
@property (nonatomic,strong) UICollectionViewFlowLayout *layout;
/**
 *  关闭按钮
 */
@property (nonatomic,strong) UIButton *closeButton;
/**
 *  保存按钮
 */
@property (nonatomic,strong) UIButton *saveButton;
/**
 *  页码
 */
@property (nonatomic,strong) UILabel *pageLabel;
/**
 *  背景
 */
@property (nonatomic,strong) UIView *bkgView;
/**
 *  记录当前的contentOffset
 */
@property(nonatomic)         CGPoint                      conOffset;


@end

@implementation PhotoBrowserVC

- (instancetype)initWithModels:(NSArray<PhotoBrowserModel *> *)models indexPath:(NSIndexPath *)indexPath {
    if (self = [super init]) {
        self.photoBrowserModels = models;
        self.indexPath = indexPath;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self prepareUI];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.indexPath.item inSection:0];
    // 设置页码
    self.pageLabel.text = [NSString stringWithFormat:@"%zd/%zd",indexPath.item+1, self.photoBrowserModels.count];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // 滚动到对应的图片
    [self.collectionView scrollToItemAtIndexPath:self.indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    
    self.conOffset = self.collectionView.contentOffset;
}

- (void)prepareUI {
    self.view.backgroundColor = [UIColor clearColor];
    // 注册cell
    [self.collectionView registerClass:[PhotoBrowserCell class] forCellWithReuseIdentifier:PhotoBrowserReuseIdentifier];
    
    [self.view addSubview:self.bkgView];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.closeButton];
    [self.view addSubview:self.saveButton];
    [self.view addSubview:self.pageLabel];
    
    self.bkgView.translatesAutoresizingMaskIntoConstraints = NO;
    self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    self.closeButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.saveButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.pageLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    self.collectionView.frame = CGRectMake(0, 0, self.view.frame.size.width + 10, self.view.frame.size.height);
    
    NSDictionary *views = @{@"cv": self.collectionView, @"cb": self.closeButton, @"sb": self.saveButton};
    
    // 水平居中
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.pageLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
    // 距离父控件top
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.pageLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:25]];
    // 关闭/保存按钮 水平方向
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-8-[cb(75)]-(>=0)-[sb(75)]-8-|" options:0 metrics:nil views:views]];
    // 关闭按钮 垂直方向
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[cb(35)]-8-|" options:0 metrics:nil views:views]];
    // 保存按钮垂直方向
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[sb(35)]-8-|" options:0 metrics:nil views:views]];
    
    // 背景视图，填充父控件
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[bv]-0-|" options:0 metrics:nil views:@{@"bv": self.bkgView}]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[bv]-0-|" options:0 metrics:nil views:@{@"bv": self.bkgView}]];
}

- (void)close {
    [SVProgressHUD dismiss];
    [self dismissViewControllerAnimated:true completion:nil];
}

- (void)save {
//    NSIndexPath *indexPath = [self.collectionView indexPathsForVisibleItems].firstObject;
//
//    PhotoBrowserCell *cell = (PhotoBrowserCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
//    
//    UIImage *image = cell.imageView.image;
//    if (image) {
//        // 保存起来
//        // completionTarget: 保存照片的回调者
//        // completionSelector: 保存照片的回调方法,不能自己定义,到头文件查看
//        // contextInfo: 上下文
//        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
//    }else {
//        [SVProgressHUD showErrorWithStatus:@"没有图片"];
//    }
}


#pragma mark - UICollectionViewDataSource,UICollectionViewDelegate>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.photoBrowserModels.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PhotoBrowserModel *model = self.photoBrowserModels[indexPath.item];
    
    PhotoBrowserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:PhotoBrowserReuseIdentifier forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor clearColor];
    
    cell.url = model.url;
    cell.delegate = self;
    
    return cell;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSLog(@"====%@ = ",[self.collectionView indexPathsForVisibleItems]);
    
    // 利用conOffset值来判断scrollView向哪边滚动
    NSIndexPath *indexPath = nil;
    if (scrollView.contentOffset.x < self.conOffset.x) { // 左边
        indexPath = [self.collectionView indexPathsForVisibleItems].firstObject;
    }else if(scrollView.contentOffset.x > self.conOffset.x) { // 右边
        indexPath = [self.collectionView indexPathsForVisibleItems].lastObject;
    }else {
        return;
    }
    self.pageLabel.text = [NSString stringWithFormat:@"%zd/%zd",indexPath.item + 1, self.photoBrowserModels.count];
    self.conOffset = scrollView.contentOffset;
}

#pragma mark - CZPhotoBrowserCellDelegate

- (UIView *)viewForTransparent {
    return self.bkgView;
}

- (void)photoBrowserCellDismissController {
    [self close];
}

- (CGRect)photoBrowserCellDismissTargetRect {
    return [self dismissTargetRect];
}

#pragma mark - 转场动画相关

/// 提供转场动画的过渡视图
- (UIImageView *)modalTempImageView {
    // 需要获取到点击小图对应的模型
    PhotoBrowserModel *model = self.photoBrowserModels[self.indexPath.item];
    
    // 获取到小图的图片
    UIImageView *imageView = model.imageView;
    
    // 创建过滤视图
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:imageView.image];
    
    // 转换坐标系
    // imageView.superview? 转换前的坐标系
    // convertRect转换CGRect
    // rect: 要转换的CGRect
    // toCoordinateSpace: 转换后的坐标系
    CGRect rect = [imageView.superview convertRect:imageView.frame toCoordinateSpace:self.view];
    
    tempImageView.frame = rect;
    
    // 设置缩放模式
    tempImageView.contentMode = imageView.contentMode;
    tempImageView.clipsToBounds = YES;
    
    return tempImageView;
}

/// 计算大图的位置,大图和小图的比例是一样的.拿小图来计算也可以
- (CGRect)modalTargetFrame {
    PhotoBrowserModel *model = self.photoBrowserModels[self.indexPath.item];

    // 获取小图
    UIImage *image = model.imageView.image;
    
    if (image) {
        // 等比例缩放到宽度等于屏幕宽度
        CGFloat newWidth = ScreenWidth;
        CGFloat newHeight = newWidth * image.size.height / image.size.width;
        
        CGFloat offsetY = 0;
        
        // 判断是长图还是短图
        if (newHeight < ScreenHeight) {
            offsetY = (ScreenHeight - newHeight) * 0.5;
        }else {
            // 图片太长，放大不好看，只有屏幕的高度
            newHeight = ScreenHeight;
        }
        return CGRectMake(0, offsetY, newWidth, newHeight);
    }else {
        return CGRectZero;
    }
}

/// 关闭视图
- (UIImageView *)dismissTempImageView {
    // 正在显示的indexPath
    NSIndexPath *indexPath = [self.collectionView indexPathsForVisibleItems].lastObject;
    
    // 正在显示的cell
    PhotoBrowserCell *cell = (PhotoBrowserCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    
    // 正在显示的大图
    UIImageView *imageView = (UIImageView *)cell.imageView;
    
    // 创建过渡视图
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:imageView.image];
    
    // 转换坐标系
    CGRect rect = [imageView.superview convertRect:imageView.frame toCoordinateSpace:self.view];
    
    // 设置frame
    tempImageView.frame = rect;
    
    // 缩放模式
    tempImageView.contentMode = UIViewContentModeScaleAspectFill;
    tempImageView.clipsToBounds = YES;
    
    return tempImageView;
}

/// dismiss最终缩放位置
- (CGRect)dismissTargetRect {
    NSIndexPath *indexPath = [self.collectionView indexPathsForVisibleItems].lastObject;
    PhotoBrowserModel *model = self.photoBrowserModels[indexPath.item];
    // 转换坐标系
    CGRect rect = [model.imageView convertRect:model.imageView.frame toCoordinateSpace:self.view];
    return rect;
}


#pragma mark - UIViewControllerTransitioningDelegate

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    // 返回控制 modal时的动画对象
    return [PhotoBrowserModalAnimation new];
}

// 返回 控制 dismiss时的动画 对象
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    return [PhotoBrowserDismissAnimation new];
}

#pragma mark - lazy load

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.bounces = NO;
        _collectionView.pagingEnabled = YES;
        _collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 10);
        _collectionView.showsHorizontalScrollIndicator = NO;
    }
    return _collectionView;
}

- (UICollectionViewFlowLayout *)layout {
    if (!_layout) {
        _layout = [UICollectionViewFlowLayout new];
        
        _layout.itemSize = self.view.bounds.size;
        _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _layout.minimumInteritemSpacing = 10;
        _layout.minimumLineSpacing = 10;
    }
    return _layout;
}

- (UIButton *)closeButton {
    if (!_closeButton) {
        _closeButton = [UIButton new];
        
        [_closeButton setBackgroundImage:[UIImage imageNamed:@"health_button_orange_line"] forState:UIControlStateNormal];
        [_closeButton setTitle:@"关闭" forState:UIControlStateNormal];
        [_closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _closeButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_closeButton addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeButton;
}

- (UIButton *)saveButton {
    if (!_saveButton) {
        _saveButton = [UIButton new];
        
        [_saveButton setBackgroundImage:[UIImage imageNamed:@"health_button_orange_line"] forState:UIControlStateNormal];
        [_saveButton setTitle:@"保存" forState:UIControlStateNormal];
        [_saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _saveButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_closeButton addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveButton;
}

- (UILabel *)pageLabel {
    if (!_pageLabel) {
        _pageLabel = [UILabel new];
        
        _pageLabel.textColor = [UIColor whiteColor];
        _pageLabel.font = [UIFont systemFontOfSize:14];
    }
    return _pageLabel;
}

- (UIView *)bkgView {
    if (!_bkgView) {
        _bkgView = [UIView new];
        _bkgView.backgroundColor = [UIColor blackColor];
    }
    return _bkgView;
}


@end









